import random
import math
import numpy as np  # 导入 numpy 模块，用于创建矩阵
import matplotlib.pyplot as plt
import pyimgur
import os
import json
import asyncio
from botpy import logging
from botpy.message import GroupMessage, Message
import base64
import psutil

async def make_map(message):
    with open(f"data/abyss/生成设定.txt", 'r') as f:
        data = json.load(f)
    large = data["深渊一层"]["面积"]
    rock_size = data["深渊一层"]["岩壁规模"]
    forest_quantity = data["深渊一层"]["丛林数量"]
    forest_size = data["深渊一层"]["丛林规模"]
    relic_quantity = data["深渊一层"]["遗迹数量"]
    relic_size = data["深渊一层"]["遗迹规模"]
    玄铁矿_quantity = data.get("深渊一层", {}).get("玄铁矿数量", 0)
    山铜矿_quantity = data.get("深渊一层", {}).get("山铜矿数量", 0)
    秘银矿_quantity = data.get("深渊一层", {}).get("秘银矿数量", 0)
    精金矿_quantity = data.get("深渊一层", {}).get("精金矿数量", 0)
    # 创建一个 100x100 的网格
    grid = [[-1 for _ in range(large)] for _ in range(large)]

    #生成洞窟
    for i in range(large):
        for j in range(large):
            x = (i - large / 2) / (large / 2)
            y = (j - large / 2) / (large / 2)
            distance = math.sqrt(x ** 2 + y ** 2)
            if distance <= 1:
                grid[i][j] = 0

    #生成岩壁
    grid0 = [row[:] for row in grid]  # 创建一个新的列表
    for a in range(int(rock_size)):
        for i in range(large):
            for j in range(large):
                x = i - large / 2
                y = j - large / 2
                distance = math.sqrt(x ** 2 + y ** 2)
                if a == 1 and int(distance) >= int(large / 2 - a) and grid[i][j] != -1:
                    grid0[i][j] = 1
                elif int(distance) >= int(large / 2 - a) and grid[i][j] != -1 and grid[i][j] != 1:
                    if grid[i+1][j] == 1 or grid[i-1][j] == 1 or grid[i][j+1] == 1 or grid[i][j-1] == 1:
                        if random.random() < 0.25:
                            grid0[i][j] = 1
        grid = [row[:] for row in grid0]  # 将新的列表赋值给grid

    #生成丛林
    a = 0
    while a < int(forest_quantity):
        x = random.randint(0, large - 1)
        y = random.randint(0, large - 1)
        if grid[x][y] != -1 and grid[x][y] != 1:
            grid[x][y] = 2
            a += 1
        else:
            continue
    grid0 = [row[:] for row in grid]  # 创建一个新的列表
    for a in range(int(forest_size * large * 0.04)):  
        for i in range(large - 1):
            for j in range(large - 1):
                if a == 1 and grid[i][j] == 2:
                    if grid[i+1][j] != -1 and grid[i+1][j] != 1:
                        grid0[i+1][j] = 2
                    if grid[i-1][j] != -1 and grid[i-1][j] != 1:
                        grid0[i-1][j] = 2
                    if grid[i][j+1] != -1 and grid[i][j+1] != 1:
                        grid0[i][j+1] = 2
                    if grid[i][j-1] != -1 and grid[i][j-1] != 1:
                        grid0[i][j-1] = 2
                elif grid[i][j] == 2:
                    if grid[i+1][j] != -1 and grid[i+1][j] != 1 and random.random() < 0.25:
                        grid0[i+1][j] = 2
                    if grid[i-1][j] != -1 and grid[i-1][j] != 1 and random.random() < 0.25:
                        grid0[i-1][j] = 2
                    if grid[i][j+1] != -1 and grid[i][j+1] != 1 and random.random() < 0.25:
                        grid0[i][j+1] = 2
                    if grid[i][j-1] != -1 and grid[i][j-1] != 1 and random.random() < 0.25:
                        grid0[i][j-1] = 2
        grid = [row[:] for row in grid0]  # 将新的列表赋值给grid
    

    #生成遗迹
    a = 0
    while a < int(relic_quantity):
        x = random.randint(0, large - 1)
        y = random.randint(0, large - 1)
        if grid[x][y] != -1:
            grid[x][y] = 3
            a += 1
        else:
            continue
    grid0 = [row[:] for row in grid]  # 创建一个新的列表
    for a in range(int(relic_size * large * 0.02)):
        for i in range(large - 1):
            for j in range(large - 1):
                directions = ["上", "下", "左", "右"]
                random.shuffle(directions)
                for direction in directions:
                    if direction == "下" and grid[i][j] == 3 and grid[i+1][j] != -1 and grid[i+1][j] != 3 and random.random() < 0.25:
                        grid0[i+1][j] = 3
                        break
                    elif direction == "上" and grid[i][j] == 3 and grid[i-1][j] != -1 and grid[i-1][j] != 3 and random.random() < 0.25:
                        grid0[i-1][j] = 3
                        break
                    elif direction == "左" and grid[i][j] == 3 and grid[i][j-1] != -1 and grid[i][j-1] != 3 and random.random() < 0.25:
                        grid0[i][j-1] = 3
                        break
                    elif direction == "右" and grid[i][j] == 3 and grid[i][j+1] != -1 and grid[i][j+1] != 3 and random.random() < 0.25:
                        grid0[i][j+1] = 3
                        break
        grid = [row[:] for row in grid0]  # 将新的列表赋值给grid

    #生成矿点
    mines = ["玄铁矿", "山铜矿", "秘银矿", "精金矿"]
    a = 0
    for mine in mines:
        while a < int(mine_quantity):
            x = random.randint(0, large - 1)
            y = random.randint(0, large - 1)
            if grid[x][y] != -1:
                grid[x][y] = 3
                a += 1
            else:
                continue

    # 绘制地图
    plt.imshow(grid, cmap='binary')
    # 添加标题
    plt.title('深界一层')
    # 隐藏坐标轴
    plt.axis('off')
    # 指定文件夹名称和文件名
    folder_name = '深渊地形图'
    file_name = 'Abyss_1 Map.png'

    # 拼接文件夹路径和文件名
    file_path = os.path.join(folder_name, file_name)

    # 如果文件夹不存在，则创建文件夹
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)

    # 如果同名文件已存在，则删除同名文件
    if os.path.exists(file_path):
        os.remove(file_path)
    
    # 保存图片到指定文件夹下，覆盖同名文件
    plt.savefig(file_path)

    # 关闭显示的窗口
    plt.close()

   # 获取当前正在运行的进程列表
   #processes = psutil.process_iter()

    # 遍历进程列表，查找同名进程并关闭
    #for process in processes:
    #    if "abyss_update" in process.cmdline():
    #        process.kill()

    # 创建新的进程
    #abyss_world = asyncio.get_event_loop()
    #abyss_world.create_task(abyss_update())

    # 读取图片为二进制数据
    with open(file_path, "rb") as f:
        image_data = f.read()

    # 将图片数据编码为 base64 字符串
    base64_data = base64.b64encode(image_data).decode("utf-8")

    if hasattr(message, 'group_openid'):
        media_0 = await message._api.post_group_file(
        group_openid=message.group_openid,
        file_type=1,
        url=None,
        srv_send_msg=False,
        file_data=base64_data
        )
        messageResult = await message._api.post_group_message(
        group_openid=message.group_openid,
        msg_type=7, 
        msg_id=message.id,
        msg_seq=1,
        content="生成成功",
        media=media_0
        )
        _log.info(messageResult)
        return
    else:
        media_0 = await message._api.post_c2c_file(
        openid=message.author.user_openid,
        file_type=1,
        url=None,
        srv_send_msg=False,
        file_data=base64_data
        )
        messageResult = await message._api.post_c2c_message(
        openid=message.author.user_openid, 
        msg_type=7, 
        msg_id=message.id, 
        msg_seq=1,
        content="生成成功",
        media=media_0
        )
        _log.info(messageResult)
        return

#async def abyss_update()